package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpuDetailMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpuDetailServiceImpl extends ServiceImpl<SpuDetailMapper,SpuDetail> implements SpuDetailService {
    @Autowired
    private SpuService spuService;

    @Autowired
    private SpecParamService specParamService;

    @Override
    public SpuDetailDTO querySpuDetailById(Long id) {
        return new SpuDetailDTO(getById(id));
    }

    @Override
    public List<SpecParamDTO> querySpecValues(Long id, Boolean searching) {
        SpuDetail spuDetail = getById(id);
        Map<Long, Object> map = JsonUtils.toMap(spuDetail.getSpecification(), Long.class,
                Object.class);
        Spu spu = spuService.getById(id);
        List<SpecParamDTO> specParamDTOS = specParamService.queryParam(spu.getCid3(), null, searching);
        List<SpecParamDTO> paramDTOList = specParamDTOS.stream().map(specParamDTO -> {
            specParamDTO.setValue(map.get(specParamDTO.getId()));
            return specParamDTO;
        }).collect(Collectors.toList());
        return paramDTOList;
    }

    @Override
    public String querySpuDetailPreview(Long id) {
        String url = getBaseMapper().querySpuDetailPreview(id);
        return url;
    }
}
